package logic

import (
	"context"
	"fmt"
	"pinduoduo/models"
	"pinduoduo/pkg"

	"pinduoduo/userrpc/internal/svc"
	"pinduoduo/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	captcha := in.Captcha
	get := models.Rdb.Get("captcharegister" + in.Mobile)
	if get.Val() != captcha {
		return nil, fmt.Errorf("验证码有误请重新填写")
	}
	code := in.SmsCode
	cmd := models.Rdb.Get("sendSmsregister" + in.Mobile)
	if cmd.Val() != code {
		return nil, fmt.Errorf("短信验证码有误请重新填写")
	}
	md5 := pkg.Md5(in.Password)
	user := models.User{
		Mobile:   in.Mobile,
		Password: md5,
	}
	err := models.Db.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败" + err.Error())
	}
	return &userrpc.UserRegisterResponse{Id: int64(user.ID), Mobile: user.Mobile}, nil
}
